<template>
  <div class="add">
    <el-alert title="添加商品信息" type="success"> </el-alert>
    <el-steps :active="active - 0" finish-status="success" class="step">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <el-form :model="addForm" ref="addForm" :rules="addFormRules">
      <el-tabs
        v-model="active"
        :tab-position="tabPosition"
        :before-leave="leaveTag"
        @tab-click="tabClick"
      >
        <el-tab-pane name="0" label="基本信息">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品库存" prop="goods_number">
            <el-input v-model="addForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addForm.goods_cat"
              :options="fenleiList"
              props.expandTrigger="hover"
              :props="listProps"
              @change="handlechangeList"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="1" label="商品参数">
          <!-- 渲染 -->
          <el-form-item
            :label="item.attr_name"
            v-for="item in ManyNumList"
            :key="item.attr_id"
          >
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                border
                :label="item1"
                v-for="(item1, i) in item.attr_vals"
                :key="i"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="2" label="商品属性">
          <el-form-item
            :label="item.attr_name"
            v-for="item in only"
            :key="item.attr_id"
          >
            <el-input v-model="item.attr_vals"> </el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="3" label="商品图片">
          <el-upload
            action="http://106.12.150.223:8090/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerObj"
            :on-success="HandleSuccess"
          >
            <el-button size="small" type="primary">上传商品图片</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane name="4" label="商品内容">
          <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
          <el-button type="primary" class="bb" @click="add">
            添加商品
          </el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 图片弹出框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="prePath" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { gettypeList, NumList, AddShop } from "../../api";
import { getToken, deleteToken } from "../../utils/token.js";
import _ from "lodash";
export default {
  name: "AddGoods",
  data() {
    return {
      dialogVisible: false,
      headerObj: {
        Authorization: getToken(),
      },
      fenleiList: [],
      active: "0",
      tabPosition: "left",
      listProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //添加商品的表单数据对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        //图片信息
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品库存", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      ManyNumList: [],
      only: [],
      prePath: "",
    };
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return;
    },
  },
  methods: {
    //获取商品分类
    getFenlei() {
      gettypeList().then((res) => {
        this.fenleiList = res.data.data;
      });
    },
    handlechangeList() {
      if (this.addForm.goods_cat.length != 3) {
        this.addForm.goods_cat = [];
      }
    },

    leaveTag(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goods_cat.length != 3) {
        this.$message({
          message: "请选择商品分类",
          type: "error",
        });
        return false;
      }
    },

    tabClick() {
      //访问动态参数
      if (this.active == "1") {
        NumList(this.cateId, "many").then((res) => {
          res.data.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
          });
          this.ManyNumList = res.data.data;
        });
      } else if (this.active == "2") {
        //静态参数
        NumList(this.cateId, "only").then((res) => {
          this.only = res.data.data;
        });
      }
    },

    //上传图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex((x) => x.pic == filePath);
      this.addForm.pics.splice(i, 1);
    },
    //图片预览
    handlePreview(file) {
      console.log(file.response.data.url);
      this.prePath = file.response.data.url;
      this.dialogVisible = true;
    },
    HandleSuccess(res) {
      if (res.meta.status == 200) {
        this.$message({
          message: res.meta.msg,
          type: "success",
        });
      }
      const picInfo = {
        pic: res.data.tmp_path,
      };
      this.addForm.pics.push(picInfo);
    },

    //添加商品
    add() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return this.$message({
            message: "请填写完整信息",
            type: "error",
          });
        }
        const formData = _.cloneDeep(this.addForm);
        formData.goods_cat = formData.goods_cat.join(",");

        //处理动态参数
        this.ManyNumList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(""),
          };
          this.addForm.attrs.push(newInfo);
        });
        //静态属性
        this.only.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        formData.attrs = this.addForm.attrs;
        console.log(formData);
        AddShop(formData).then((res) => {
          if (res.data.meta.status == 201) {
            this.$message({
              message: res.data.meta.msg,
              type: "success",
            });
            this.$router.push('/admin/goods')
          }else{
            this.$message({
              message: res.data.meta.msg,
              type: "error",
            });
          }
        });
      });
    },
  },

  created() {
    this.getFenlei();
  },
};
</script>

<style scoped lang="less">
.bb {
  margin-top: 15px;
}
/deep/.ql-editor {
  min-height: 300px !important;
}

.el-button {
  width: 86px;
  height: 32px;
  padding: 0;
}
.step {
  padding: 0 80px;
  box-sizing: border-box;
  margin: 20px 0;
}
/deep/.el-checkbox {
  margin: 0 0 0 10px !important;
}
/deep/.el-form-item__label {
  width: 100%;
  text-align: left;
}
.add {
  background-color: #fff;
  padding: 10px;
}
</style>